<!--
 * @Descripttion: 
 * @version: 
 * @Author: wl
 * @Date: 2020-06-17 17:15:22
 * @LastEditors: wl
 * @LastEditTime: 2020-08-20 20:12:36
-->
<template>
  <div>
    <el-form ref="form" :model="form" :rules="formRules" class="addform" label-width="80px">
      <el-divider>基本信息</el-divider>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" clearable></el-input>
      </el-form-item>
      <el-form-item label="人员类型" prop="type">
        <el-select @change="changeType" v-model="form.type" placeholder="请选择" clearable>
          <el-option v-for="item in houseList" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="gender" required label="性别">
        <el-radio-group v-model="form.gender">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="icNumber" label="一人一卡">
        <el-input v-model="form.icNumber" clearable></el-input>
      </el-form-item>
      <el-form-item label="证件类型" prop="documentType">
        <el-select v-model="form.documentType" placeholder="请选择" clearable @change="documentTypeChange">
          <el-option
            v-for="item in sysCertificateType"
            :key="item.DID"
            :label="item.name"
            :value="item.DID"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="证件号" prop="idCard">
        <el-row>
          <el-col :span="22">
            <el-input v-model="form.idCard" clearable></el-input>
          </el-col>
          <el-col :span="2" class="icon-list__tips">
            <el-tooltip placement="top" effect="light" style="padding: 10px">
              <div slot="content">
                <p>证件号：</p>
                <p>1.若为大陆用户请直接输入自己的身份证号。</p>
                <p>2.若为境外用户，请输入护照号。</p>
              </div>
              <i class="el-icon-warning"></i>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="有效日期">
        <el-row>
          <el-col :span="11">
            <el-date-picker
              v-model="form.idCard_startTime"
              class="normal"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              clearable
            ></el-date-picker>
          </el-col>
          <el-col :span="2">到</el-col>
          <el-col :span="11" class="icon-list__tips">
            <el-date-picker
              v-model="form.idCard_endTime"
              class="normal"
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
              clearable
            ></el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="选择小区" prop="CID">
        <el-select filterable @change="change_CID" v-model="form.CID" placeholder="请选择" clearable>
          <el-option v-for="item in villageList" :key="item.CID" :label="item.name" :value="item.CID"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          form.type !== '029f992a-d6e4-4421-baeb-88c9d2a15f3f' &&
          form.type !== '3a14543e-2808-431c-a0cf-98a64f41bd78'
        "
        required
        style="width: 90%"
        label="地址"
      >
        <div class="row">
          <el-select
            v-show="!isXiangCun"
            prop="BID"
            style="width: 18%"
            v-model="BID"
            @change="pickdong"
            placeholder
            clearable
          >
            <el-option v-for="item in maxdong" :key="item.BID" :label="item.name" :value="item.BID"></el-option>
          </el-select>
          <span v-show="!isXiangCun">栋</span>
          <el-select
            v-show="!isXiangCun"
            prop="UID"
            style="width: 18%"
            v-model="UID"
            @change="pickdanyuan"
            placeholder
            clearable
          >
            <el-option v-for="item in maxdanyuan" :key="item.UID" :label="item.name" :value="item.UID"></el-option>
          </el-select>
          <span v-show="!isXiangCun">单元</span>
          <el-select
            v-show="!isXiangCun"
            prop="FID"
            style="width: 18%"
            v-model="FID"
            @change="pickceng"
            placeholder
            clearable
          >
            <el-option v-for="item in maxceng" :key="item.FID" :label="item.name" :value="item.FID"></el-option>
          </el-select>
          <span v-show="!isXiangCun">层</span>
          <el-select prop="HID" style="width: 18%" v-model="HID" placeholder clearable>
            <el-option v-for="item in maxhao" :key="item.HID" :label="item.name" :value="item.HID"></el-option>
          </el-select>
          号
        </div>
      </el-form-item>
      <div class="addform">
        <el-form-item label="民族" prop="nation">
          <el-select v-model="form.nation" placeholder="请选择" clearable>
            <el-option v-for="(item, idx) in nations" :key="idx" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学历">
          <el-select v-model="form.educationType" placeholder="请选择" clearable>
            <el-option v-for="item in education" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="政治面貌">
          <el-select v-model="form.political" placeholder="请选择" clearable>
            <el-option v-for="item in politics" :key="item.DID" :label="item.name" :value="item.DID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="婚姻状态">
          <el-radio v-model="form.maritalStatus" label="0">未婚</el-radio>
          <el-radio v-model="form.maritalStatus" label="1">已婚</el-radio>
        </el-form-item>
      </div>
      <div v-if="form.type == 'f109bf87-931e-45f6-894c-adcdb3b7e8bb'" class="addform">
        <el-divider>境外人员</el-divider>
        <el-form-item label="英文名">
          <el-input v-model="form.englishName" clearable></el-input>
        </el-form-item>
        <el-form-item label="英文姓">
          <el-input v-model="form.englishSurname" clearable></el-input>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="国家" prop="nation">
          <el-select filterable v-model="form.country" placeholder="请选择" clearable>
            <el-option v-for="(item, idx) in countries" :key="idx" :label="item.label" :value="item.label">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入境日期">
          <el-date-picker
            v-model="form.entryTime"
            class="normal"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="停留有效期至">
          <el-date-picker
            v-model="form.stayToTime"
            class="normal"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            clearable
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="签证证件种类">
          <el-select v-model="form.visaType" placeholder="请选择" clearable>
            <el-option
              v-for="item in sys_visa_type"
              :key="item.DID"
              :label="item.name"
              :value="item.DID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签证证件号码">
          <el-input v-model="form.visa_num" clearable></el-input>
        </el-form-item>
        <el-form-item label="入境口岸">
          <el-input v-model="form.entryPort" clearable></el-input>
        </el-form-item>
        <el-form-item label="入境事由">
          <el-input v-model="form.entrySubject" clearable></el-input>
        </el-form-item>
        <el-form-item label="签发机关">
          <el-input v-model="form.signOffice" clearable></el-input>
        </el-form-item>
        <el-form-item label="何处来">
          <el-input v-model="form.whereFrom" clearable></el-input>
        </el-form-item>
        <el-form-item label="何处去">
          <el-input v-model="form.whereTo" clearable></el-input>
        </el-form-item>
        <el-form-item label="住宿日期">
          <el-date-picker
            v-model="form.liveTime"
            class="normal"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="拟离开日期">
          <el-date-picker
            v-model="form.leaveMayTime"
            class="normal"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="离开日期">
          <el-date-picker
            v-model="form.leaveTime"
            class="normal"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="居住地派出所">
          <el-input v-model="form.police" clearable></el-input>
        </el-form-item>
        <el-form-item required prop="register" label="临时登记">
          <el-radio-group v-model="form.register">
            <el-radio label="0">未登记</el-radio>
            <el-radio label="1">已登记</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <el-form-item label="上传头像" prop="photo" v-if="!SpecialNew">
        <el-upload
          ref="uploadImg"
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeRead"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="form.photo" :src="global.baseUrlImage + 'avatar/' + form.photo" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <i style="color: red">*头像必须上传</i>
      </el-form-item>
    </el-form>
    <div class="dialog-footer cen">
      <el-button @click="canaelSumbit">取 消</el-button>
      <el-button type="primary" @click.native="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import Camera from './camera';
import { Loading } from 'element-ui';
import fileUtils from '@/utils/fileUtils.js';
import { checkMobile, checkIdcard, checkName, getBase64 } from '@/common/utils';
export default {
  components: {
    Camera
  },
  props: {
    /* 表单数据 */
    propsForm: {
      type: Object,
      default: {}
    },
    SpecialNew: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      addImgUrl: '',
      selections: [],
      pageResult: [],
      optionsSex: [
        {
          value: 0,
          label: '男'
        },
        {
          value: 1,
          label: '女'
        }
      ],
      loading: false,
      // 人员标记
      documentTypeFlag: true, //是否显示身份证18位验证
      registOption: [], //注册类型
      dictList: {},
      nations: this.$store.state.app.nations,
      form: {},
      formRules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          },
          { validator: checkName, trigger: 'blur' }
        ],
        idCard: [
          {
            required: true,
            message: "请输入证件号码",
            trigger: "blur"
          },
          { validator: checkIdcard, trigger: 'blur' }
        ],
        documentType: [{ required: true, message: '请选择证件类型', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        //
        gender:[{ required: true, message: "请选择一个性别", trigger: "blur" }],
        register:[{ required: true, message: "请选择一个登记", trigger: "blur" }],
        type: [{ required: true, message: "人员类型必填", trigger: "blur" }],
        CID: [{ required: true, message: "小区必选", trigger: "blur" }]
      },
      houseList: [],
      personList: [],
      // 小区列表
      villageList: [],
      // 标记已有列表
      signList: [],
      //新的标记列表
      newSignList: [],
      perID: '',
      perName: '',
      maxdong: [{ name: '1', BID: 'a521a5c7-c2ca-4938-abc7-f320d76d3558' }],
      maxdanyuan: [],
      maxceng: [],
      maxhao: [],
      BID: '',
      UID: '',
      FID: '',
      HID: '',
      dong: '',
      danyuan: '',
      ceng: '',
      hao: '',
      education: [],
      politics: [],
      countries: this.$store.state.app.countries || [],
      getCommunity: [],
      sysCertificateType: [],
      isAbroad: false,
      sys_visa_type: {},
      isXiangCun: false
    };
  },

  methods: {
    //人员类型改变
    changeType(e) {
      if (
        this.form.type === '029f992a-d6e4-4421-baeb-88c9d2a15f3f' ||
        this.form.type === '3a14543e-2808-431c-a0cf-98a64f41bd78'
      ) {
        this.BID = '';
        this.UID = '';
        this.FID = '';
        this.HID = '';
      }
    },
    initHouse(t) {
      if (t === 'dongInt') this.maxdong = [];
      this.maxdanyuan = [];
      this.maxceng = [];
      this.maxhao = [];
      this.BID = '';
      this.UID = '';
      this.FID = '';
      this.HID = '';
    },
    judgeType(cid) {
      let coms = this.villageList.find(it => it.CID === cid);
      if (coms && coms.type === '1cec27e8-8831-4e87-9180-061aeac3d9d1') return true; // 乡村房
      return false;
    },
    // 根据选择的小区cid获取楼栋
    async change_CID(e) {
      if (!e) {
        this.initHouse('dongInt');
        return;
      }
      let isXiangCun = this.judgeType(e);
      this.isXiangCun = isXiangCun;
      if (isXiangCun) {
        this.pickceng();
        return;
      }
      this.getMaxDong();
    },
    async getMaxDong() {
      let res = await this.$api.build.building_list_weChat({
        page: 1,
        limit: 1000,
        type: 1,
        sort: { name: -1 },
        where: { CID: this.form.CID }
      });
      if (res.code !== 0) return;
      this.maxdong = res.data;
      this.initHouse();
    },

    //选择完楼栋
    async pickdong(e) {
      let res = await this.$api.build.building_list_weChat({
        page: 1,
        limit: 1000,
        type: 2,
        sort: { name: -1 },
        where: { BID: e, CID: this.form.CID }
      });
      if (res.code !== 0) return;
      this.maxdanyuan = res.data;
      this.maxceng = [];
      this.maxhao = [];
      this.UID = '';
      this.FID = '';
      this.HID = '';
    },
    //证件类型选择
    documentTypeChange(e) {
      if (e !== "13bb793c-1ddf-40bc-9a9e-64474f71bc82") {
        this.documentTypeFlag = false;
      } else {
        this.documentTypeFlag = true;
      }
    },
    async pickdanyuan(e) {
      let res = await this.$api.build.building_list_weChat({
        page: 1,
        limit: 1000,
        type: 3,
        sort: { name: -1 },
        where: { CID: this.form.CID, UID: e }
      });
      if (res.code !== 0) return;
      this.maxceng = res.data;
      this.maxhao = [];
      this.FID = '';
      this.HID = '';
    },
    async pickceng(e) {
      let res = await this.$api.build.building_list_weChat({
        page: 1,
        limit: 1000,
        type: 4,
        sort: { name: -1 },
        where: { CID: this.form.CID, FID: e }
      });
      if (res.code !== 0) return;
      this.maxhao = res.data;

      this.BID = res.data[0].BID;
      this.UID = res.data[0].UID;
      this.FID = res.data[0].FID;
      this.HID = '';
    },
    getDirList() {
      this.dictList = JSON.parse(sessionStorage.getItem('dictData'));
      this.registOption = this.dictList.sys_persion_source;
      this.registOption.map(item => {
        item.value = item.DID;
        item.name = item.name;
      });
    },
    handleAvatarSuccess(res, file) {
      this.addImgUrl = URL.createObjectURL(file.raw);
    },
    beforeRead(file) {
      return new Promise(resolve => {
        fileUtils.getOrientation(file).then(orient => {
          let reader = new FileReader();
          let img = new Image();
          reader.onload = e => {
            img.src = e.target.result;
            img.onload = async () => {
              let width = 600,
                height = 600 * (img.height / img.width);
              const data = await fileUtils.rotateImage(img, width, height, orient);
              const newFile = await fileUtils.dataURLtoFile(data, file.name);
              resolve(this.upLoad(newFile));
            };
          };
          reader.readAsDataURL(file);
        });
      });
    },
    // 编辑添加图片
    async upLoad(param) {
      let rs = await getBase64(param);
      var paramd = {
        img: rs
      };
      let res = await this.$api.imgAdd.addimgPer(paramd);
      if (res.code !== 0) return;
      this.$set(this.form, 'photo', res.id);
    },
    // 获取楼栋单元层名
    getAddressNmae(type) {
      let name = '';
      switch (type) {
        case 'BID':
          let bid = this.maxdong.find(it => it.BID === this.BID);
          name = bid && bid.name ? bid.name : '';
          break;
        case 'UID':
          let uid = this.maxdanyuan.find(it => it.UID === this.UID);
          name = uid && uid.name ? uid.name : '';
          break;
        case 'FID':
          let fid = this.maxceng.find(it => it.FID === this.FID);
          name = fid && fid.name ? fid.name : '';
          break;
        case 'HID':
          let hid = this.maxhao.find(it => it.HID === this.HID);
          name = hid && hid.name ? hid.name : '';
          break;
        default: {
        }
      }
      return name;
    },
    // 新增提交
    async submitForm() {
      if (
        this.form.type !== '029f992a-d6e4-4421-baeb-88c9d2a15f3f' &&
        this.form.type !== '3a14543e-2808-431c-a0cf-98a64f41bd78' &&
        !this.isXiangCun &&
        (this.BID == '' || this.UID == '' || this.FID == '' || this.HID == '')
      ) {
        this.$alert('请选择完整地址！', '提示', {
          confirmButtonText: '确定'
        });
        return;
      }
      if (this.form.idCard_startTime > this.form.idCard_endTime) {
        this.$alert('有效期开始时间请大于结束时间！', '提示', {
          confirmButtonText: '确定'
        });
        return;
      }
      if (!this.SpecialNew && !this.form.photo) {
        this.$alert('请先上传照片！', '提示', {
          confirmButtonText: '确定'
        });
        return;
      }

      this.$refs.form.validate(async valid => {
        if (!valid) return;
        let loadingInstance = Loading.service();
        let rs = await this.$api.PlatformEntry.get_community_msg({
          CID: this.form.CID
        });
        let address_t = '';
        if (rs.data && rs.data.address) {
          address_t = rs.data.address;
        }
        if (this.isXiangCun && this.HID) {
          // 乡镇房（只有户）
          this.form.address = address_t + this.getAddressNmae('HID') + '号';
        } else if (!this.isXiangCun && this.BID && this.UID && this.FID && this.HID) {
          this.form.address =
            address_t +
            this.getAddressNmae('BID') +
            '栋' +
            this.getAddressNmae('UID') +
            '单元' +
            this.getAddressNmae('FID') +
            '层' +
            this.getAddressNmae('HID') +
            '号';
        } else {
          this.form.address = address_t;
        }
        let params = { ...this.form };
        params.auditType = 2;
        params.houser = {
          BID: this.BID,
          UID: this.UID,
          FID: this.FID,
          HID: this.HID
        };
        //特殊人员新增 SpecialNew
        if (this.SpecialNew) {
          delete params.photo;
          let paramJson = JSON.stringify(params);
          let res = await this.$api.PlatformEntry.SpecialAdd(paramJson);
          if (res.code !== 0) {
            loadingInstance.close();
            this.$message({
              type: "info",
              message: "添加失败"
            });
          }else{
            this.$message({
              type: "success",
              message: "添加成功"
            });
          }
          loadingInstance.close();
          this.$emit('refresh');
          return;
        }
        // 非特殊新增
        let res = null;

        if (this.form._id) {
          // 修改人员
          res = await this.$api.PlatformEntry.sys_person_edit(params);
        } else {
          // 新增
          res = await this.$api.PlatformEntry.personAdd(params);
        }

        if (res.code !== 0) {
          loadingInstance.close();
          this.$message({
            type: 'info',
            message: '添加失败'
          });
        }
        this.examine(res.rs, loadingInstance);
      });
    },
    canaelSumbit() {
      this.$emit('getMsg');
    },
    //新增后直接审批
    examine(row, loadingInstance) {
      let formPass = Object.assign(row, {
        auditType: 1,
        auditPID: this.perID,
        perID: this.perID,
        perName: this.perName,
        describe: '通过'
      });
      this.$api.personPass.personAudit(formPass).then(res => {
        if (res.Success == true) {
          if (res.result.result.ok == 1) {
            this.$message({
              type: 'success',
              message: '操作成功'
            });
          } else {
            this.$message('添加成功，但需手动审核！');
          }
          loadingInstance.close();
          this.$refs['form'].resetFields();
          this.$refs.uploadImg.clearFiles();
          this.$emit('refresh');
        } else {
          loadingInstance.close();
          this.$message(res.msg);
        }
      });
    }
  },
  async mounted() {
    this.villageList = await this.getCommunitiesMix();
    if (this.propsForm.CID) {
      this.form = { ...this.propsForm };
      this.isXiangCun = this.judgeType(this.form.CID);
      if (
        this.form.type !== '029f992a-d6e4-4421-baeb-88c9d2a15f3f' &&
        this.form.type !== '3a14543e-2808-431c-a0cf-98a64f41bd78' &&
        this.form.houser.length
      ) {
        await this.getMaxDong();
        await this.pickdong(this.form.houser[0].BID);
        await this.pickdanyuan(this.form.houser[0].UID);
        await this.pickceng(this.form.houser[0].FID);
        this.BID = this.form.houser[0].BID;
        this.UID = this.form.houser[0].UID;
        this.FID = this.form.houser[0].FID;
        this.HID = this.form.houser[0].HID;
      }
    }
    this.$nextTick(() => {
      let dictList = JSON.parse(sessionStorage.getItem('dictData'));
      this.houseList = dictList.sys_person_type;
      this.source = dictList.sys_persion_source;
      this.signList = dictList.sys_person_sign;
      this.education = dictList.sys_education_type;
      this.politics = dictList.sys_politics_type;
      this.sysCertificateType = dictList.sys_certificate_type;
      this.sys_visa_type = dictList.sys_visa_type;
      var userID = JSON.parse(sessionStorage.getItem('userID'));
      this.perID = userID._id;
      this.perName = userID.name;
    });
  }
};
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.addform {
  margin: 0 auto;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  justify-content: space-between;
  .el-form-item {
    width: 48%;
  }
  .el-form-item__content {
    .el-cascader {
      width: 100%;
    }
    .el-select {
      width: 100%;
    }
  }
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
